<?php

namespace GamesBundle\Services;
use GamesBundle\Entity\GameAwards;
use GamesBundle\Entity\GameNperRecord;
use GamesBundle\Entity\GamesUserOrder;
use GamesBundle\Entity\UserScoreLog;
use GamesBundle\Services\ContainerAware;

/**
 * 数据处理
 * @author  coffey  <coffey@nligo.com>
 * @time    2017/2/21
 */
class HandleOrderData extends ContainerAware
{
    /**
     * @auhtor  coffey
     *
     * 下注
     * @param int $gameId
     * @param string $str
     * @param array $GameNperRecordIdInfo
     * @return array
     */
    public function createData($str = '',$GameNperRecordIdInfo = array())
    {
        $em = $this->container->get('doctrine')->getManager();
        $userInfo = $this->getUser();
        $result = $catNumArr = $specTypeArr = $specInfo = array();
        $result['code'] = 0;
        $result['data'] = '';
        $em = $this->container->get('doctrine')->getManager();
        $speclist = $em->getRepository('GamesBundle:GamesSpec')->findAll();
        if(!empty($userInfo) && !empty($speclist) && !empty($str))
        {
            foreach ($speclist as $k=>$v)
            {
                if(explode($v->getSpecSign(),$str) == true)
                {
                    $arr = explode($v->getSpecSign(),$str);
                    $firstFiledDef = $v->getFirstFiledDef() ? $v->getFirstFiledDef() : 1;
                    $newStr = str_replace($v->getSpecSign(),",",$str);
                    break;
                }
            }
            if(count($arr) == 3)
            {
                $catNumArr = !empty($arr[0]) ? $arr[0] : '';
                $specTypeArr = !empty($arr[1]) ? $this->mbStrSplit($arr[1]) : array();
                $bettingMoney = !empty($arr[2]) ? $arr[2] : 0;
            }
            elseif(count($arr) == 2)
            {
                $catNumArr = $firstFiledDef;
                $specTypeArr = !empty($arr[0]) ? $this->mbStrSplit($arr[0]) : array();
                $bettingMoney = !empty($arr[1]) ? $arr[1] : 0;
            }
            if(count($arr) == 3 || count($arr) ==2)
            {
                $em->getConnection()->beginTransaction();
                try
                {
                    for($t=0;$t<strlen($catNumArr);$t++)
                    {
                        for ($i = 0; $i <count($specTypeArr); $i++) {
                            $userOrder = new GamesUserOrder();
                            $userOrder->setGameNperRecordId($GameNperRecordIdInfo);
                            $userOrder->setNper($GameNperRecordIdInfo->getNper());
                            $userOrder->setUserId($userInfo);
                            $userOrder->setBitMoney($bettingMoney);
                            $userOrder->setCarNum($catNumArr[$t]);
                            if(is_numeric($specTypeArr[$i]) == true)
                            {
                                $userOrder->setGameType(1);
                                $userOrder->setGameTypeName($this->_changeNum($specTypeArr[$i]));
                            }
                            else
                            {
                                $userOrder->setGameType(2);
                                $userOrder->setGameTypeName($specTypeArr[$i]);
                            }
                            $userOrder->setOrderStr($newStr);
                            $em->persist($userOrder);
                            $em->flush($userOrder);
                            $result['data'][$i][$t] = $specTypeArr[$i].'='.$catNumArr[$t].'-'.$bettingMoney;
                        }
                    }
                    $result['data'] = implode(';',array_map(create_function('$v','return implode(",",$v);'),$result['data']));
                    $countSocre = $bettingMoney*strlen($catNumArr)*count($specTypeArr);
                    $userSocre = $userInfo->getUserTotalScore();
                    if($countSocre<$userSocre)
                    {
                        $nowSocre = $userSocre-$countSocre;
                        $userInfo->setUserTotalScore($nowSocre);
                        $em->persist($userInfo);
                        $em->flush($userInfo);
                        $scoreLog = new UserScoreLog();
                        $scoreLog->setUserId($userInfo);
                        $scoreLog->setNowScore($nowSocre);
                        $scoreLog->setOperScore($countSocre);
                        $em->persist($scoreLog);
                        $em->flush($scoreLog);
                    }
                    $em->getConnection()->commit();
                    $em->flush();
                }catch (\Exception $e)
                {
                    $em->getConnection()->rollBack();
                    $result['code'] = 1;
                }

            }
        }
        else
        {
            $result['code'] = 1;
        }
        return !empty($result) ? $result : array();

    }

    /**
     * @author  coffey
     *
     * 获取最新开奖信息
     * @return GameNperRecord
     */
    public function getNper()
    {
        $url   = $this->container->getParameter('caipiao_url');
        $data = array(
            'name' => $this->container->getParameter('caipiao_name'),
            'format' => $this->container->getParameter('caipiao_format'),
            'uid' => $this->container->getParameter('caipiao_uid'),
            'token' => $this->container->getParameter('caipiao_token'),
            'num'   =>  $this->container->getParameter('caipiao_limit'),
        );
        $lotteylist = json_decode($this->container->get('curl_data')->curl($url, 'get',$data),true);
        $doctrine = $this->container->get('doctrine');
        $em = $doctrine->getManager();
        foreach ($lotteylist as $k=>$v)
        {
            $gamenper = $em->getRepository('GamesBundle:GameNperRecord')->findOneBy(array('nper'=>$k));
            if(empty($gamenper))
            {
                $gamenper = new GameNperRecord();
            }
            $gamenper->setNper($k);
            $gamenper->getOpenAt(strtotime($v['dateline']));
            $lotteyNumArr = explode(',',$v['number']);
            $gamenper->setLotteryNumberA($lotteyNumArr[0]);
            $gamenper->setLotteryNumberB($lotteyNumArr[1]);
            $gamenper->setLotteryNumberC($lotteyNumArr[2]);
            $gamenper->setLotteryNumberD($lotteyNumArr[3]);
            $gamenper->setLotteryNumberE($lotteyNumArr[4]);
            $gamenper->setLotteryNumberF($lotteyNumArr[5]);
            $gamenper->setLotteryNumberG($lotteyNumArr[6]);
            $gamenper->setLotteryNumberH($lotteyNumArr[7]);
            $gamenper->setLotteryNumberI($lotteyNumArr[8]);
            $gamenper->setLotteryNumberj($lotteyNumArr[9]);
            $gamenper->setLotNumber($v['number']);
            $em->persist($gamenper);
            $em->flush($gamenper);
            $newGameNper = $em->getRepository('GamesBundle:GameNperRecord')->findOneBy(array('nper'=>$k+1));
            if(empty($newGameNper))
            {
                $newGameNper = new GameNperRecord();
            }
            $newGameNper->setNper($k+1);
            $em->persist($newGameNper);
            $em->flush($newGameNper);
            $this->_matchNum($gamenper);
            $this->matchLot($k);
            echo $k;
        }
        return $gamenper;
    }

    /**
     * @author  coffey
     *
     * 取消   撤回下注
     * @param int $userId
     * @param int $nper
     * @return mixed
     */
    public function cancelOrder($userId = 0,$nper = 0)
    {
        $userInfo = $this->getUser();
        $result['code'] = 0;
        $result['data'] = '';
        if(!empty($userInfo) && !empty($userId) && !empty($nper))
        {
            $em = $this->container->get('doctrine')->getManager();
            $speclist = $em->getRepository('GamesBundle:GamesUserOrder')->findBy(array('nper'=>$nper,'userId'=>$userId));
            $countSocre = 0;
            foreach ($speclist as $k=>$v)
            {
                $v->setStatus(1);
                $em->persist($v);
                $em->flush($v);
                $countSocre += $v->getBitMoney();
            }
            $nowSocre = $userInfo->getUserTotalScore()+$countSocre;
            $userInfo->setUserTotalScore($nowSocre);
            $em->persist($userInfo);
            $em->flush($userInfo);

            $scoreLog = new UserScoreLog();
            $scoreLog->setUserId($userInfo);
            $scoreLog->setConsStatus(1);
            $scoreLog->setNowScore($nowSocre);
            $scoreLog->setOperScore($countSocre);
            $em->persist($scoreLog);
            $em->flush($scoreLog);
        }
        else
        {
            $result['code'] = 1;
        }
        return $result;
    }

    /**
     * @auhtor  coffey
     *
     * 匹配号码生成龙虎大小单双数据
     * @param array $gamenperInfo
     */
    private function _matchNum($gamenperInfo = array())
    {
        $doctrine = $this->container->get('doctrine');
        $em = $doctrine->getManager();
        if(!empty($gamenperInfo))
        {
            $countGy = $gamenperInfo->getLotteryNumberA()+$gamenperInfo->getLotteryNumberB();
            $gamenperInfo->setCountGy($countGy);
            $tB = $this->is_odd($countGy)==true ? '单' : '双';
            $gamenperInfo->setTB($tB);
            $tA = $countGy<= 11 ? '小' : '大';
            $gamenperInfo->setTA($tA);
            $lha = $gamenperInfo->getLotteryNumberA()>$gamenperInfo->getLotteryNumberj() ? '龙' : '虎';
            $lhb = $gamenperInfo->getLotteryNumberB()>$gamenperInfo->getLotteryNumberI() ? '龙' : '虎';
            $lhc = $gamenperInfo->getLotteryNumberC()>$gamenperInfo->getLotteryNumberH() ? '龙' : '虎';
            $lhd = $gamenperInfo->getLotteryNumberD()>$gamenperInfo->getLotteryNumberG() ? '龙' : '虎';
            $lhe = $gamenperInfo->getLotteryNumberE()>$gamenperInfo->getLotteryNumberF() ? '龙' : '虎';
            $fileds = $tA.','.$tB.','.$lha.','.$lhb.','.$lhc.','.$lhd.','.$lhe;
            $gamenperInfo->setLha($lha);
            $gamenperInfo->setLhb($lhb);
            $gamenperInfo->setLhc($lhc);
            $gamenperInfo->setLhd($lhd);
            $gamenperInfo->setLhe($lhe);
            $gamenperInfo->setFileds($fileds);
            $em->persist($gamenperInfo);
            $em->flush($gamenperInfo);
        }
    }

    /**
     * @auhtor  coffey
     *
     * 匹配排名中奖（123/123/200）这种
     * @param int $gameId
     * @param string $str
     * @param array $GameNperRecordIdInfo
     * @return array
     */
    public function matchLot($nper = 0)
    {
        $result['code'] = 0;
        $result['data'] = '';
        $doctrine = $this->container->get('doctrine');
        $em = $doctrine->getManager();
        $lotlist = $em->getRepository('GamesBundle:GamesUserOrder')->loadValidOrder($nper);
        if(!empty($lotlist))
        {
            foreach ($lotlist as $k=>$v)
            {
                if($v->getGameType() == 1)
                {
                    $lot_str = $v->getGameNperRecordId()->getLotNumber();
                    if(in_array($v->getGameTypeName(),explode(',',$lot_str)))
                    {
                        $gameAw = new GameAwards();
                        $gameAw->setOrderId($v);
                        $gameAw->setGameNperRecordId($v->getGameNperRecordId());
                        $em->persist($gameAw);
                        $em->flush($gameAw);
                    }
                }
                if($v->getGameType() == 2)
                {
                    $lot_str = $v->getGameNperRecordId()->getFileds();
                    if(in_array($v->getGameTypeName(),explode(',',$lot_str)))
                    {
                        $gameAw = new GameAwards();
                        $gameAw->setOrderId($v);
                        $gameAw->setGameNperRecordId($v->getGameNperRecordId());
                        $em->persist($gameAw);
                        $em->flush($gameAw);
                    }
                }


            }
        }
        return $result;

    }


    /**
     * @auhtor  coffey
     *
     * 转换数字为01这种标准格式
     * @param $num
     * @return int|string
     */
    private function _changeNum($num)
    {
        if($num == 0)
        {
            $num = 10;
        }
        else
        {
            $num = '0'.$num;
        }
        return $num;
    }
    /**
     * @author  coffey
     *
     * 将字符串分割为数组
     * @param $string
     * @param int $len
     * @return array
     */
    private function mbStrSplit ($string, $len=1) {
        $start = 0;
        $strlen = mb_strlen($string);
        while ($strlen) {
            $array[] = mb_substr($string,$start,$len,"utf8");
            $string = mb_substr($string, $len, $strlen,"utf8");
            $strlen = mb_strlen($string);
        }
        return $array;
    }

    //判断奇数，是返回TRUE，否返回FALSE
    private function is_odd($num){
        return (is_numeric($num)&($num&1));
    }
    //判断偶数，是返回TRUE，否返回FALSE
    private function is_even($num){
        return (is_numeric($num)&(!($num&1)));
    }


    /**
     * @auhtor  coffey
     *
     * 判断用户能否下单
     * @param int $gameId
     * @param string $str
     * @return array
     */
    public function is_create($str = '',$GameNperRecordIdInfo = array())
    {
        $em = $this->container->get('doctrine')->getManager();
        $userInfo = $this->getUser();
        $result = $catNumArr = $specTypeArr = $specInfo = array();

    }
}